package com.yumeko.api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

/**
 * @program: zookeeper
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-26 01:30
 */
public class CreateNote implements Watcher {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper("192.168.106.128:2182", 5000, new CreateNote());
        System.out.println(zooKeeper.getState());
        countDownLatch.await();
        System.out.println(zooKeeper.getState());

    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        //当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            //调⽤创建节点⽅法
            try {
                createNodeSynec();
            } catch (Exception e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }

    }

    /**
     * path ：节点创建的路径
     * data[] ：节点创建要保存的数据，是个byte类型的
     * acl ：节点创建的权限信息(4种类型)
     * ANYONE_ID_UNSAFE : 表示任何⼈
     * AUTH_IDS ：此ID仅可⽤于设置ACL。它将被客户机验证的ID替换。
     * OPEN_ACL_UNSAFE ：这是⼀个完全开放的ACL(常⽤)-->world:anyone
     * CREATOR_ALL_ACL ：此ACL授予创建者身份验证ID的所有权限
     * createMode ：创建节点的类型(4种类型)
     * PERSISTENT：持久节点
     * PERSISTENT_SEQUENTIAL：持久顺序节点
     * EPHEMERAL：临时节点
     * EPHEMERAL_SEQUENTIAL：临时顺序节点
     * String node = zookeeper.create(path,data,acl,createMode);
     */
    private void createNodeSynec() throws UnsupportedEncodingException, KeeperException, InterruptedException {
        String yumekoCreate = zooKeeper.create("/yumekoCreate1", "持久节点内容".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        String yumekoCreate1 = zooKeeper.create("/yumekoCreate2", "持久节点顺序内容".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        String yumekocreate2 = zooKeeper.create("/yumekocreate3", "临时节点内容".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        String yumekocreate3 = zooKeeper.create("/yumekocreate4", "临时节点顺序".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("创建的节点是:" + yumekoCreate);
        System.out.println("创建的节点是:" + yumekoCreate1);
        System.out.println("创建的节点是:" + yumekocreate2);
        System.out.println("创建的节点是:" + yumekocreate3);
    }
}
